﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Common.Utils {
  public class DiskDriver {

    [DllImport("kernel32.dll")]
    private static extern int GetVolumeInformation(
            string lprootpathname,
            string lpvolumenamebuffer,
            int nvolumenamesize,
            ref long lpvolumeserialnumber,
            int lpmaximumcomponentlength,
            int lpfilesystemflags,
            string lpfilesystemnamebuffer,
            int nfilesystemnamesize);

    public static string GetHardDiskNumberByVolume(string drverId = "C") {
      const int max_filename_len = 256;
      long retval = 0;
      int lpmaximumcomponentlength = 0;
      int lpfilesystemflags = 0;
      string lpvolumenamebuffer = null;
      string lpfilesystemnamebuffer = null;
      string driver = drverId.Trim('\\').Trim(':');
      int i = GetVolumeInformation(
          driver + @":\",
          lpvolumenamebuffer,
          max_filename_len,
          ref retval,
          lpmaximumcomponentlength,
          lpfilesystemflags,
          lpfilesystemnamebuffer,
          max_filename_len);

      return string.Format("{0}", retval);
    }


    public static string GetSpaceSize(long spaceSize) {
      if (spaceSize > (long)1024 * 1024 * 1024 * 1024) {
        return string.Format("{0:f}TB", (long)spaceSize / 1024 / 1024 / 1024 / 1024);
      } else if (spaceSize > 1024 * 1024 * 1024) {
        return string.Format("{0:f}GB", (long)spaceSize / 1024 / 1024 / 1024);
      } else if (spaceSize > 1024 * 1024) {
        return string.Format("{0:f}MB", (long)spaceSize / 1024);
      } else if (spaceSize > 1024) {
        return string.Format("{0:f}KB", (long)spaceSize / 1024);
      } else {
        return string.Format("{0:f}B", spaceSize);
      }
    }


  }
}
